﻿using AutoMapper;
using DevProtocolApi.Dtos.system;
using Infrastructure.Extensions;
using Microsoft.AspNetCore.Mvc;
using Model.EntityModel.Auth;
using Service.IService.ISysService;

namespace DevProtocolApi.Controllers.sysControllers
{
    /// <summary>
    /// 部门管理控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class DeptController : BaseController
    {
        private readonly IDeptService _deptService;
        private readonly ILogger<DeptController> _logger;
        private readonly IMapper _mapper;

        public DeptController(
            IDeptService deptService,
            ILogger<DeptController> logger,
            IMapper mapper)
        {
            _deptService = deptService;
            _logger = logger;
            _mapper = mapper;
        }
        /// <summary>
        /// 添加新部门（同步）
        /// </summary>
        [HttpPost]
        public IActionResult Add(DeptMasterDto dto)
        {
            try
            {
                var deptMaster = _mapper.Map<Dept>(dto);
                deptMaster.CreatedBy= CurrentUser.UserName;
                deptMaster.CreatedAt = DateTime.UtcNow;
                bool success = _deptService.CreateDept(deptMaster);
                return success
                    ? Success("添加成功")
                    : Failed("添加失败");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"添加部门失败: {dto.Name}");
                return Failed($"添加失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取部门树结构
        /// </summary>
        [HttpGet]
        public IActionResult GetDeptTree()
        {
            try
            {
                var data = _deptService.GetDeptTree();
                return data.Count > 0
                    ? Success(data)
                    : Failed("查询失败");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取部门树失败");
                return Failed($"查询失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 更新部门信息（异步）
        /// </summary>
        [HttpPut]
        public async Task<IActionResult> UpdateAsync(DeptMasterDto dto)
        {
            try
            {
                var deptMaster = _mapper.Map<Dept>(dto);
                bool success = await _deptService.UpdateDeptAsync(deptMaster);
                return success ? Success("更新成功") : Failed("更新失败");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"更新部门失败: {dto.Id}");
                return Failed($"更新失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 删除部门（异步）
        /// </summary>
        [HttpDelete]
        public async Task<IActionResult> DeleteAsync(string id)
        {
            try
            {
                bool success = await _deptService.DeleteDeptAsync(id);
                return success ? Success("删除成功") : Failed("删除失败");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"删除部门失败: {id}");
                return Failed($"删除失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 根据ID获取部门信息（异步）
        /// </summary>
        [HttpGet("{id}")]
        public async Task<IActionResult> GetByIdAsync(string id)
        {
            try
            {
                var dept = await _deptService.GetDeptByIdAsync(id);
                return dept != null
                    ? Success(dept)
                    : Failed("部门不存在");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取部门信息失败: {id}");
                return Failed($"获取失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取所有部门（异步）
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetAllAsync()
        {
            try
            {
                var depts =  _deptService.GetAllDepts();
                return Success(depts);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取所有部门失败");
                return Failed($"获取失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取部门层级结构（异步）
        /// </summary>
        [HttpGet("hierarchy")]
        public async Task<IActionResult> GetHierarchyAsync()
        {
            try
            {
                var hierarchy = await _deptService.GetDeptHierarchyAsync();
                return Success(hierarchy);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取部门层级结构失败");
                return Failed($"获取失败: {ex.Message}");
            }
        }
    }


}
